import pylab
import cv2
import numpy as np

# 二值化阈值处理(cv2.THRESH_BINARY)
lena=cv2.imread('train_image/sky.png',cv2.IMREAD_GRAYSCALE)
# pylab.subplot(1,2,1)
# pylab.gray()
# pylab.imshow(lena)
#
#
# t,res=cv2.threshold(lena, 127, 255,cv2.THRESH_BINARY)
# # pylab灰度图是三通道，如果用单通道 进行展示会造成图片失真，所以这里进行通道扩展
# res = np.concatenate((np.expand_dims(res, axis = 2), np.expand_dims(res, axis = 2), np.expand_dims(res, axis = 2)),
#                          axis = -1)
# pylab.subplot(1,2,2)
# pylab.imshow(res)
# pylab.show()

# 反二值化阈值处理(cv2.THRESH_BIN_INV)
# pylab.subplot(1,2,1)
# pylab.gray()
# pylab.imshow(lena)
# t,res=cv2.threshold(lena,127,255,cv2.THRESH_BINARY_INV)
# # pylab灰度图是三通道，如果用单通道 进行展示会造成图片失真，所以这里进行通道扩展
# res = np.concatenate((np.expand_dims(res, axis = 2), np.expand_dims(res, axis = 2), np.expand_dims(res, axis = 2)),
#                          axis = -1)
# pylab.subplot(1,2,2)
# pylab.imshow(res)
# pylab.show()

# 截断阈值化处理(cv2.THRESH_TRUNC)
# 截断阈值化处理会将图像中大于阈值的像素点的值设定为阈值，小于或等于阈值的像素点保持不变
# pylab.subplot(1,2,1)
# pylab.gray()
# pylab.imshow(lena)
# t,res=cv2.threshold(lena,127,255,cv2.THRESH_TRUNC)
# # pylab灰度图是三通道，如果用单通道 进行展示会造成图片失真，所以这里进行通道扩展
# # res = np.concatenate((np.expand_dims(res, axis = 2), np.expand_dims(res, axis = 2), np.expand_dims(res, axis = 2)),
# #                          axis = -1)
# pylab.subplot(1,2,2)
# pylab.imshow(res)
# pylab.show()


# 超阈值零处理(cv2.THRESH_TOZERO_INV)
pylab.subplot(1,2,1)
pylab.gray()
pylab.imshow(lena)
t,res=cv2.threshold(lena,127,255,cv2.THRESH_TOZERO_INV)
# pylab灰度图是三通道，如果用单通道 进行展示会造成图片失真，所以这里进行通道扩展
res = np.concatenate((np.expand_dims(res, axis = 2), np.expand_dims(res, axis = 2), np.expand_dims(res, axis = 2)),
                         axis = -1)
pylab.subplot(1,2,2)
pylab.imshow(res)
pylab.show()

# 低阈值零处理(cv2.THRESH_TOZERO)
pylab.subplot(1,2,1)
pylab.imshow(lena)
t,res=cv2.threshold(lena,127,255,cv2.THRESH_TOZERO)
pylab.subplot(1,2,2)
pylab.imshow(res)
pylab.show()


# Otus处理
pylab.subplot(1,2,1)
pylab.imshow(lena)
t2,res=cv2.threshold(lena,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
pylab.subplot(1,2,2)
pylab.imshow(res)
pylab.show()
print("寻找的最佳阈值为{}".format(t2))


# 自适应阈值处理
pylab.subplot(1,3,1)
pylab.imshow(lena)
res_1=cv2.adaptiveThreshold(lena,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,71,3)
# pylab灰度图是三通道，如果用单通道 进行展示会造成图片失真，所以这里进行通道扩展
res_1 = np.concatenate((np.expand_dims(res_1, axis = 2), np.expand_dims(res_1, axis = 2), np.expand_dims(res_1, axis = 2)),
                         axis = -1)
pylab.subplot(1,3,2)
pylab.imshow(res_1)
res_2=cv2.adaptiveThreshold(lena,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,71,3)
# pylab灰度图是三通道，如果用单通道 进行展示会造成图片失真，所以这里进行通道扩展
res2 = np.concatenate((np.expand_dims(res_2, axis = 2), np.expand_dims(res_2, axis = 2), np.expand_dims(res_2, axis = 2)),
                         axis = -1)
pylab.subplot(1,3,3)
pylab.imshow(res_2)
pylab.show()